package org.opens.lambda.date;

import org.junit.Test;

import java.time.*;
import java.time.temporal.ChronoUnit;

public class InstantAndDurationAndPeriod {

    /**
     * 说明:
     *      1. java8中将时间的区分精细化了, LocalDate用来描述日期, LocalTime来描述时间:
     *          - 而Instant(中文: 瞬间) 用来描述时间点, 就是保持当时的状态; (其实LocalTime也能做, 但是没有进行分类)
     *          - Duration(中文: 持续时间) 用来描述一段时间, 就是持续的事件. (同样LocalTime也能实现, 但是相当于是没有分类, 会很混乱)
     *
     */
    @Test
    public void test1() throws InterruptedException {
        Instant start = Instant.now();
        Thread.sleep(1000);

        Instant end = Instant.now();
        Duration between = Duration.between(start, end);

        System.out.println(between.toMillis());
    }

    /**
     * 输出:
     *      17:14:31.600
     *      16:14:31.600
     *      18:14:31.600
     *      -3600000
     *      3600000
     * 说明:
     *      1. 使用Duration计算出两个Instant之间的间隔时间并转换为人性化显示.
     */
    @Test
    public void test2() {
        LocalTime now = LocalTime.now();

        //给当前时间加1小时
        LocalTime minus1 = now.minus(1, ChronoUnit.HOURS);
        //给当前时间减1小时
        LocalTime minus2 = now.minus(-1, ChronoUnit.HOURS);

        System.out.println(now);
        System.out.println(minus1);
        System.out.println(minus2);

        System.out.println(Duration.between(now, minus1).toMillis());
        System.out.println(Duration.between(now, minus2).toMillis());
    }

    /**
     * 输出:
     *      1
     *      10
     *      1
     * 说明:
     *      1. 与普通的计算间隔不同, 这个是以周期进行计算的, 以1年为周期进行计算.
     *      2. 之所以getDays输出1是因为计算时忽略年份, 计算的是周期差.
     */
    @Test
    public void test3() {
        Period period = Period.between(LocalDate.of(2014, 3, 10), LocalDate.of(2016, 1, 11));

        System.out.println(period.getDays());
        System.out.println(period.getMonths());
        System.out.println(period.getYears());
    }

}
